package com.zone.vehicle.superapp.view.home.home;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.vehicle.lib.search.FloatingSearchView;
import com.zone.vehicle.lib.search.suggestions.SearchSuggestionsAdapter;
import com.zone.vehicle.lib.search.suggestions.model.SearchSuggestion;
import com.zone.sdk.module.comment.entity.SearchResultEntity;
import com.zone.vehicle.lib.search.suggestions.SuperSearchSuggestion;
import com.zone.vehicle.superapp.databinding.FragmentHomeAppBinding;
import com.zone.vehicle.superapp.model.HomeViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import com.zone.vehicle.superapp.view.common.enums.ActionEnum;
import com.zone.vehicle.superapp.view.common.listener.ActionListener;
import com.zone.vehicle.superapp.view.home.home.main.AppHorizontalFragment;
import com.zone.vehicle.superapp.view.home.home.search.SearchResultFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.zone.vehicle.superapp.view.common.enums.ActionEnum.ACTION_FOCUS_CLEARED;
import static com.zone.vehicle.superapp.view.common.enums.ActionEnum.ACTION_SEARCH_FOCUS;
import static com.zone.vehicle.superapp.view.common.enums.ActionEnum.ACTION_SEARCH_TEXT_CHANGED;
import static com.zone.vehicle.superapp.view.home.HomeFragment.HOME_APP_FRAGMENT;
import static com.zone.vehicle.superapp.view.home.HomeFragment.RECOMMEND_FRAGMENT;

/**
 * 首页（横屏展示页）
 * 下级界面：横向滚动列表、搜索
 */
public class HomeAppFragment extends BaseFragment {

    private static final String TAG = HomeAppFragment.class.getSimpleName();

    private FragmentHomeAppBinding binding;

    private HomeViewModel viewModel;

    public static final String APP_HORIZONTAL_FRAGMENT = "AppHorizontalFragment";
    public static final String SEARCH_RESULT_FRAGMENT = "SearchResultFragment";

    private FragmentPagerAdapter adapter;

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHomeAppBinding.inflate(inflater);
        init();
        return binding.getRoot();
    }

    @Override
    public void initFragmentPages() {
        super.initFragmentPages();
        addPage(new AppHorizontalFragment());
        addPage(new SearchResultFragment());
    }

    private void hideMethod() {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(binding.floatingSearch.getWindowToken(), 0);
    }

    private void init() {
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(HomeViewModel.class);

        binding.btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.setSearchData(binding.floatingSearch.getQuery());
                clearSuggestions();
                hideMethod();
            }
        });

        binding.floatingSearch.setLeftSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.setSearchData(binding.floatingSearch.getQuery());
                hideMethod();
            }
        });

        binding.recommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "recommend onClick=" + v);
                changePage(RECOMMEND_FRAGMENT);
            }
        });
        initFloatingSearch();

        addListener(new ActionListener() {
            @Override
            public boolean onAction(ActionEnum action) {
                Log.d(TAG, "onAction=" + action);
                if (action == ACTION_FOCUS_CLEARED) {
                    if (ObjectUtils.isEmpty(viewModel.getSearchAppList().getValue())
                            && ObjectUtils.isEmpty(viewModel.getSearchData().getValue())) {
                        changePage(APP_HORIZONTAL_FRAGMENT);
//                        binding.viewpager.setCurrentItem(0);
                        return true;
                    }
                    return false;
                } else if (action == ACTION_SEARCH_FOCUS) {
                    changePage(SEARCH_RESULT_FRAGMENT);
//                    binding.viewpager.setCurrentItem(1);
                    return true;
                }
                return false;
            }

            @Override
            public boolean onPageChanged(String pageName) {
                Log.d(TAG, "onPageChanged=" + pageName);
                switch (pageName) {
                    case APP_HORIZONTAL_FRAGMENT:
                        binding.btnSearch.setVisibility(View.GONE);
                        binding.recommend.setVisibility(View.VISIBLE);
                        clearSearch();
                        binding.viewpager.setCurrentItem(0);
                        return true;
                    case SEARCH_RESULT_FRAGMENT:
                        binding.btnSearch.setVisibility(View.VISIBLE);
                        binding.recommend.setVisibility(View.GONE);
                        changePage(HOME_APP_FRAGMENT);
                        binding.viewpager.setCurrentItem(1);
                        return true;
                    default:
                        return false;
                }
            }
        });
        adapter = new FragmentPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @Override
            public int getCount() {
                return getPages().size();
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                return getPage(position);
            }
        };
        binding.viewpager.setAdapter(adapter);
    }

    private void initFloatingSearch() {
        binding.floatingSearch.setBackgroundColor(Color.TRANSPARENT);
        binding.floatingSearch.setOnHomeActionClickListener(new FloatingSearchView.OnHomeActionClickListener() {
            @Override
            public void onHomeClicked() {
                viewModel.clearSearch();
                changePage(APP_HORIZONTAL_FRAGMENT);
                binding.btnSearch.setVisibility(View.GONE);
                binding.recommend.setVisibility(View.VISIBLE);
                binding.viewpager.setCurrentItem(0);
            }
        });
        binding.floatingSearch.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
            @Override
            public void onSearchTextChanged(String oldQuery, String newQuery) {
                onAction(ACTION_SEARCH_TEXT_CHANGED);
                if (!oldQuery.equals("") && newQuery.equals("")) {
                    changePage(APP_HORIZONTAL_FRAGMENT);
                    clearSuggestions();
                } else {
                    changePage(SEARCH_RESULT_FRAGMENT);
                    viewModel.searchSuggestions(newQuery);
//                    viewModel.indexSearch(newQuery);
                }
                Log.d(TAG, "onSearchTextChanged()");
            }
        });
        binding.floatingSearch.setOnClearSearchActionListener(new FloatingSearchView.OnClearSearchActionListener() {
            @Override
            public void onClearSearchClicked() {
                clearSearch();
                binding.btnSearch.setVisibility(View.GONE);
                binding.recommend.setVisibility(View.VISIBLE);
                binding.viewpager.setCurrentItem(0);
            }
        });
        binding.floatingSearch.setOnHomeActionClickListener(new FloatingSearchView.OnHomeActionClickListener() {
            @Override
            public void onHomeClicked() {
                clearSearch();
                binding.btnSearch.setVisibility(View.GONE);
                binding.recommend.setVisibility(View.VISIBLE);
                binding.viewpager.setCurrentItem(0);
            }
        });
        viewModel.getSearchSuggestionsList().observe(getViewLifecycleOwner(), new Observer<List<SearchResultEntity>>() {
            @Override
            public void onChanged(List<SearchResultEntity> appEntities) {
                if (ObjectUtils.isNotEmpty(appEntities)) {
                    List<SuperSearchSuggestion> searchSuggestions = new ArrayList<>();
                    for (int i = 0; i < appEntities.size(); i++) {
                        SearchResultEntity appEntity = appEntities.get(i);
                        SuperSearchSuggestion suggestion = new SuperSearchSuggestion();
                        suggestion.setSearch(appEntity.getName());
                        searchSuggestions.add(suggestion);
                    }
                    binding.floatingSearch.swapSuggestions(searchSuggestions);
                    binding.floatingSearch.hideProgress();
                }
            }
        });
        binding.floatingSearch.setOnLeftMenuClickListener(new FloatingSearchView.OnLeftMenuClickListener() {
            @Override
            public void onMenuOpened() {
                Log.d(TAG, "onMenuOpened()");
            }

            @Override
            public void onMenuClosed() {
                Log.d(TAG, "onMenuClosed()");
            }
        });
        binding.floatingSearch.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
            @Override
            public void onSuggestionClicked(final SearchSuggestion searchSuggestion) {
                viewModel.setSearchData(searchSuggestion.getBody());
//                binding.floatingSearch.setSearchText(searchSuggestion.getBody());
                clearSuggestions();
                hideMethod();
                Log.d(TAG, "onSuggestionClicked()");
            }

            @Override
            public void onSearchAction(String query) {
                viewModel.setSearchData(query);
//                binding.floatingSearch.setSearchText(query);
//                binding.floatingSearch.clearSuggestions();
//                clearSuggestions();
                Log.d(TAG, "onSearchAction()");
            }
        });

        binding.floatingSearch.setOnFocusChangeListener(new FloatingSearchView.OnFocusChangeListener() {
            @Override
            public void onFocus() {
                onAction(ACTION_SEARCH_FOCUS);
                Log.d(TAG, "onFocus()");
            }

            @Override
            public void onFocusCleared() {
//                onAction(ACTION_FOCUS_CLEARED);
                Log.d(TAG, "onFocusCleared()");
            }
        });

        binding.floatingSearch.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
            @Override
            public void onBindSuggestion(View suggestionView, ImageView leftIcon,
                                         TextView textView, SearchSuggestion item, int itemPosition) {
//                Log.d(TAG, "onBindSuggestion()");
            }
        });
    }

    private void clearSearch() {
        viewModel.clearSearch();
//        binding.floatingSearch.setSearchText("");
    }

    private void clearSuggestions(){
        binding.floatingSearch.clearSuggestions();
        hideInput(binding.floatingSearch);
    }

}